<template>
  <div class="equipment-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="24">
        <el-form
          :model="queryForm"
          label-width="120px"
          @submit.native.prevent
        >
          <el-row>
            <el-col :xl="6" :md="8">
              <el-form-item label="客户名称:">
                <el-input
                  v-model.trim="queryForm.name"
                  placeholder=""
                  clearable
                  @keyup.enter.native="queryData()"
                />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="负责人:">
                <el-input
                  v-model.trim="queryForm.principal"
                  placeholder=""
                  clearable
                  @keyup.enter.native="queryData()"
                />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="手机号:">
                <el-input
                  v-model.trim="queryForm.phoneNumber"
                  placeholder=""
                  clearable
                  @keyup.enter.native="queryData()"
                />
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="价格策略:">
                <el-select
                  v-model="queryForm.priceStrategy"
                  filterable
                  clearable
                  @change="queryData()"
                >
                  <el-option
                    v-for="(item, index) in priceStrategyList"
                    :key="index"
                    :value="item.id"
                    :label="item.strategyName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="客户组织:">
                <el-select
                  v-model="queryForm.organizationCode"
                  placeholder="请选择客户组织"
                  @change="selectDept($event)"
                >
                  <el-option label="请选择客户组织" value=""></el-option>
                  <el-option
                    v-for="item in deptList"
                    :key="item.fnumber"
                    :label="item.fname"
                    :value="item.fnumber"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="客户分类:">
                <el-select
                  v-model="queryForm.customerTypeCode"
                  placeholder="请选择客户分类"
                >
                  <el-option label="请选择客户分类" value=""></el-option>
                  <el-option
                    v-for="item in customerTypeList"
                    :key="item.fnumber"
                    :label="item.fnumber + '(' + item.fname + ')'"
                    :value="item.fnumber"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="业务员:">
                <el-select
                  v-model="queryForm.bizCode"
                  placeholder="请选择业务人员"
                  @change="queryData()"
                >
                  <el-option label="请选择业务人员" value=""></el-option>
                  <el-option
                    v-for="item in bizList"
                    :key="item.fnumber"
                    :label="item.fname"
                    :value="item.fnumber"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="客户类型:">
                <el-select v-model="queryForm.customerKindCode" placeholder="请选择客户类型"
                           @change="queryData()">
                  <el-option label="请选择客户类型" value=""></el-option>
                  <el-option v-for="item in customerKindList" :key="item.no" :label="item.label" :value="item.no"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="6" :md="8">
              <el-form-item label="物流线路:">
                <el-select
                  v-model="queryForm.wuliuCode"
                  filterable
                  clearable
                  @change="queryData()"
                >
                  <el-option
                    v-for="(item, index) in wuliuList"
                    :key="index"
                    :value="item.fnumber"
                    :label="item.fdataValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="1">
              <el-form-item label="">
                <div style="display: flex;">
                  <el-button
                    icon="el-icon-search"
                    type="primary"
                    @click="queryData"
                  >
                    查询
                  </el-button>
                  <el-button
                    icon="el-icon-edit"
                    type="success"
                    @click="showBatchUpdate = true;batchUpdateCustomerTypeCode = ''"
                  >
                    批改分类
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </vab-query-form-left-panel>
      <!--<vab-query-form-left-panel :span="24">
        <el-button
          v-permissions="['admin', 'staff']"
          icon="el-icon-plus"
          type="primary"
          @click="handleEdit(null)"
        >
          新增客户
        </el-button>
      </vab-query-form-left-panel>-->
      <vab-query-form-bottom-panel></vab-query-form-bottom-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      height="520"
      border
      stripe
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
    >
      <el-table-column
        width="260"
        show-overflow-tooltip
        prop="name"
        fixed="left"
        label="客户名称"
      ></el-table-column>
      <el-table-column
        width="180"
        show-overflow-tooltip
        prop="organizationName"
        label="客户组织"
      ></el-table-column>
      <el-table-column
        width="180"
        show-overflow-tooltip
        prop="customerTypeName"
        label="客户分类"
      ><template slot-scope="scope">
        {{ scope.row.customerTypeCode + '(' + scope.row.customerTypeName + ')' }}
      </template></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="bizName"
        width="100"
        label="业务员"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="customerKindName"
        width="100"
        label="客户类型"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="principal"
        width="100"
        label="负责人"
      ></el-table-column>
      <el-table-column
        width="120"
        show-overflow-tooltip
        prop="phoneNumber"
        label="手机号码"
      ></el-table-column>
      <el-table-column
        width="200"
        show-overflow-tooltip
        prop="priceStrategyName"
        label="价格策略"
      ></el-table-column>
      <el-table-column
        width="300"
        show-overflow-tooltip
        prop="wuliuName"
        label="物流线路"
      ></el-table-column>
      <el-table-column
        width="100"
        show-overflow-tooltip
        prop="wuliuOrder"
        label="物流排序"
        align="right"
      ></el-table-column>
      <el-table-column
        width="100"
        show-overflow-tooltip
        prop="orderQty"
        label="起送量"
        align="right"
      ></el-table-column>
      <el-table-column
        width="100"
        show-overflow-tooltip
        prop="freightFee"
        label="运费"
        align="right"
      ></el-table-column>
	  <el-table-column
	    width="100"
	    show-overflow-tooltip
	    prop="depositAmount"
	    label="预付款金额"
	    align="right"
	  ></el-table-column>
	  <el-table-column
	    width="100"
	    show-overflow-tooltip
	    prop="lockAmount"
	    label="锁定金额"
	    align="right"
	  ></el-table-column>
	  <el-table-column
	    show-overflow-tooltip
	    prop="noDepositOrder"
	    width="120"
	    label="预付模式"
	  >
	    <template slot-scope="scope">
	      <el-tag v-if="scope.row.noDepositOrder == 1" type="default">
	        正常
	      </el-tag>
	      <el-tag
	        v-else-if="scope.row.noDepositOrder == 2"
	        type="success"
	      >
	        预付
	      </el-tag>
	    </template>
	  </el-table-column>
	  <el-table-column
	    show-overflow-tooltip
	    prop="overDepositOrder"
	    width="120"
	    label="超预付额度"
	  >
	  </el-table-column>
	  
      <el-table-column
        show-overflow-tooltip
        prop="approved"
        width="80"
        label="审批状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="!scope.row.approved" type="default" disable-transitions>
            未审核
          </el-tag>
          <el-tag
            v-else-if="scope.row.approved == '1'"
            type="success"
            disable-transitions
          >
            已审批
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="approved"
        width="80"
        label="审批权限"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="(scope.row.permiss & 1) == 1"
            type="success"
            disable-transitions
          >
            可
          </el-tag>
          <el-tag v-else type="default">不可</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="approved"
        width="80"
        label="报表查看"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="(scope.row.permiss & 2) == 2"
            type="success"
            disable-transitions
          >
            可
          </el-tag>
          <el-tag v-else type="default">不可</el-tag>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="操作" width="550">
        <template #default="{ row }">
          <el-button
            v-show="!row.approved"
            v-permissions="['admin', 'staff']"
            icon="el-icon-finished"
            type="warning"
            @click="handleApproval(row)"
          >
            审批
          </el-button>
          <el-button
            v-permissions="['admin', 'staff']"
            icon="el-icon-edit"
            type="primary"
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            icon="el-icon-edit"
            type="success"
            @click="handleResetPwd(row)"
          >
            修改密码
          </el-button>
          <el-button
            v-permissions="['admin', 'staff']"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
          <el-button
            v-show="row.approved == 1"
            v-permissions="['admin', 'staff']"
            :icon="row.locked ? 'el-icon-lock' : 'el-icon-unlock'"
            :type="row.locked ? 'danger' : 'primary'"
            @click="handleLockUnlock(row)"
          >
            {{ row.locked ? '已锁' : '未锁' }}
          </el-button>
		  <el-button
		    v-permissions="['admin', 'staff']"
		    icon="el-icon-edit"
		    type="primary"
		    @click="showDepositDetails(row)"
		  >
		    预付款明细
		  </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :page-size="queryForm.pageSize"
      :layout="layout"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <el-dialog title="批改客户分类"
      :visible.sync="showBatchUpdate"
      width="340px"
      top="5vh"
    >
      <div style="margin-bottom: 20px;">根据列表页面的过滤条件批量更新客户分类</div>
      <el-select
        v-model="batchUpdateCustomerTypeCode"
        placeholder="请选择客户分类"
      >
        <el-option
          v-for="item in customerTypeList"
          :key="item.fnumber"
          :label="item.fnumber + '(' + item.fname + ')'"
          :value="item.fnumber"
        ></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showBatchUpdate = false">取 消</el-button>
        <el-button type="primary" @click="handleBatchUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrganization,
  getCustomerTypeList,
  getCustomerTypeChildrenList,
  getBizList,
  getWuliuList, getDept, getCustomerLastTypeList,
} from '@/api/erp'
import {
  getList,
  doLock,
  doUnlock,
  doDelete,
  doApproved,
  doResetCustomerPwd,
  doBatchUpdate,
} from '@/api/customerManagement'

import { getApprovedList } from '@/api/priceStrategyManagement'

export default {
  name: 'CustomerManagementList',
  components: {},
  data() {
    return {
      list: null,
      listLoading: true,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      selectRows: '',
      elementLoadingText: '正在加载...',
      //客户组织
      deptList: [],
      //客户类型
      customerTypeList: [],
      //客户小分类
      customerTypeChildrenList: [],
      //业务员
      bizList: [],
      customerKindList: [{ no: '1', label: '渠道店' }, { no: '2', label: '加盟店' }, { no: '3', label: '代加工' }],
      //价格策略
      priceStrategyList: [],
      //物流
      wuliuList: [],
      batchUpdateCustomerTypeCode: '',
      showBatchUpdate: false,
      queryForm: {
        pageNo: 1,
        pageSize: 50,
        name: '',
        principal: '',
        phoneNumber: '',
        bizCode: '',
        organizationCode: '',
        customerTypeCode: '',
        customerTypeChildCode: '',
        customerKindCode: '',
        wuliuCode: '',
        priceStrategy: '',
      },
    }
  },
  created() {


    // let conditon = sessionStorage.getItem('customerQueryCondition')
    // if(conditon){
    //     let obj = JSON.parse(conditon);
    //     this.queryForm =  Object.assign({}, obj)

    //     console.info(this.queryForm)
    // }
    this.init()
    this.fetchData()
  },
  methods: {

    async init(){
      let res = await getDept()
      this.deptList = res
      res = await getCustomerLastTypeList()
      this.customerTypeList = res
      // let res = await getOrganization()
      // this.organizationList = res
      // res = await getCustomerTypeList()
      // this.customerTypeList = res
      this.priceStrategyList = await getApprovedList()
      //物流路线
      this.wuliuList = await getWuliuList()
      //this.shoukuanList= await getShoukuanList()
    },

    setSelectRows(val) {
      this.selectRows = val
    },
    handleApproval(row) {
      if (!row.priceStrategy) {
        this.$baseAlert('由于该客户还未绑定价格策略，不能进行审批操作!')
        return
      }

      this.$baseConfirm('你确认要审批通过该客户吗？', null, async () => {
        this.listLoading = true

        await doApproved(row.id)
        this.$baseMessage('审批成功', 'success')
        this.fetchData()
      })
    },
    handleEdit(row) {
      this.$router.push({
        name: 'CustomerManage',
        params: { customerInfo: row },
      })
    },
    handleDelete(row) {
      if (row.id) {
        this.$baseConfirm('你确定要删除当前客户吗', null, async () => {
          await doDelete(row.id)
          this.$baseMessage('客户删除成功', 'success')
          this.fetchData()
        })
      }
    },
    handleResetPwd(row) {
      let _this = this
      this.$prompt('请输入密码', '修改密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputType: 'password',
        inputErrorMessage: '密码不能为空',
      })
        .then(async ({ value }) => {
          await doResetCustomerPwd({
            id: row.id,
            password: value,
          })

          this.$message({
            type: 'success',
            message: '密码更新成功',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入',
          })
        })
    },
    handleLockUnlock(row) {
      if (row.id) {
        let msg = '你确定要锁住当前用户吗？'
        if (row.locked) {
          msg = '你确定要解锁当前用户吗？'
        }
        this.$baseConfirm(msg, null, async () => {
          if (row.locked) {
            await doUnlock(row.id)
          } else {
            await doLock(row.id)
          }
          this.$baseMessage('数据操作成功', 'success')
          this.fetchData()
        })
      }
    },
	showDepositDetails(row) {
		this.$router.push({
		  name: 'DepositManage',
		  params: { customerInfo: row },
		})
	},
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val
      this.fetchData()
    },
    queryData() {
      this.queryForm.pageNo = 1
      this.fetchData()
    },
    async fetchData() {

      //保存检索条件
      //sessionStorage.setItem('customerQueryCondition', JSON.stringify(this.queryForm))

      this.listLoading = true
      const { records, totalElement } = await getList(this.queryForm)

      this.list = records
      this.total = totalElement
      setTimeout(() => {
        this.listLoading = false
      }, 300)
    },

    //客户大分类
    async selectDept(event) {
      this.customerTypeChildrenList = []
      this.queryForm.customerTypeChildCode = ''
      this.queryForm.customerTypeChildName = ''

      //业务员
      this.bizList = []
      this.queryForm.bizCode = ''
      this.queryForm.bizName = ''

      if (this.queryForm.organizationCode) {
        //获取业务员
        for(let i = 0; i < this.deptList.length; i++) {
          let dept = this.deptList[i]
          if (dept.fnumber === this.queryForm.organizationCode) {
            this.bizList = await getBizList(dept.fname)
            break
          }
        }
      }
    },
    async handleBatchUpdate() {
      if (!this.batchUpdateCustomerTypeCode) {
        this.$message.error('请选择分类')
        return
      }
      try {
        await this.$confirm('确定批量修改吗', {
          title: '确认'
        })
      } catch(e) {
        return
      }
      let param = Object.assign({batchUpdateCustomerTypeCode: this.batchUpdateCustomerTypeCode}, this.queryForm);
      let result = this.$baseLodash.find(this.customerTypeList, (o) => {
        return o.fnumber === this.batchUpdateCustomerTypeCode
      })
      param.batchUpdateCustomerTypeName = result ? result.fname : ''
      try {
        let res = await doBatchUpdate(param)
        if (!res.res) {
          this.$message.error('处理异常')
          return
        }
        this.showBatchUpdate = false
        this.$message.success(`已更新${ res.count }个客户`)
        return this.queryData()
      } catch(e) {
        this.$message.error(e? (e.message || e): '未知错误')
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.el-row {
  &:last-child {
    margin-bottom: 20px;
  }
}
.el-table__body {
  .el-link:last-child {
    margin-left: 10px;
  }
}

::v-deep {
  .el-select {
    width: 100%;
  }
}
</style>
